package commit;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.utils.StorageUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import co.yeye.test.MainActivity;
import co.yeye.test.R;
import images.selecter.ImgFileListActivity;
import models.UserObject;

/**
 * Created by yeye on 15/2/18.
 */
public class WriteDiscovery extends ActionBarActivity {

    Button tittle;
    ImageView image_1,image_2,image_3;
    ImageView image_4,image_5,image_6;
    ImageView image_7,image_8,image_9;
    ImageView user_img;
    TextView user_name;
    private LinearLayout layout_1,layout_2,layout_3;
    EditText content;
    //ArrayList<Bitmap> bitmapList = new ArrayList<Bitmap>();      // 存放图片的bitmap
    ArrayList<String> pathList = new ArrayList<String>();   // 存放照片的绝对路径
    UserObject userObject = new UserObject();
    ImageLoader imageLoader;
    DisplayImageOptions options;

    boolean isCommitting = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.write_discovery_layout);

        ActionBar actionBar = this.getSupportActionBar();
        actionBar.setTitle("发布活动信息");
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.blue));

        tittle = (Button) findViewById(R.id.tittle);
        image_1 = (ImageView) findViewById(R.id.iv_img_1);
        image_2 = (ImageView) findViewById(R.id.iv_img_2);
        image_3 = (ImageView) findViewById(R.id.iv_img_3);
        image_4 = (ImageView) findViewById(R.id.iv_img_4);
        image_5 = (ImageView) findViewById(R.id.iv_img_5);
        image_6 = (ImageView) findViewById(R.id.iv_img_6);
        image_7 = (ImageView) findViewById(R.id.iv_img_7);
        image_8 = (ImageView) findViewById(R.id.iv_img_8);
        image_9 = (ImageView) findViewById(R.id.iv_img_9);
        layout_1 = (LinearLayout) findViewById(R.id.image_set_top);
        layout_2 = (LinearLayout) findViewById(R.id.image_set_middle);
        layout_3 = (LinearLayout) findViewById(R.id.image_set_bottom);
        content = (EditText) findViewById(R.id.edit);

        tittle.setVisibility(View.GONE);

        setImageClickListener(0);
        setInputImages();

        imageLoaderInit();
        // 获取用户信息并配置图片和姓名
        userObject = MainActivity.getInstance().getUser();
        user_img = (ImageView) findViewById(R.id.user_img);
        user_name = (TextView) findViewById(R.id.user_name);
        user_name.setText(userObject.getUser_name());
        imageLoader.displayImage(userObject.getUri(),user_img,options,null);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode==100){
                String sdStatus = Environment.getExternalStorageState();
                if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                    Log.i("TestFile",
                            "SD card is not avaiable/writeable right now.");
                    return;
                }
                String name = new DateFormat().format("yyyyMMdd_hhmmss",
                        Calendar.getInstance(Locale.CHINA)) + ".jpg";
                Toast.makeText(this, name, Toast.LENGTH_LONG).show();
                Bundle bundle = data.getExtras();
                Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式

                FileOutputStream b = null;
                File file = new File("/sdcard/.MyOptoUploadImg/");
                file.mkdirs();// 创建文件夹
                String fileName = "/sdcard/.MyOptoUploadImg/"+name;

                try {
                    b = new FileOutputStream(fileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        b.flush();
                        b.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //bitmapList.add(bitmap);
                pathList.add(fileName);
                setInputImages();
                setImageClickListener(pathList.size());
            }
        }
        // 保存一系列的图片
        if(resultCode==RESULT_OK){
            if(requestCode==101){
                boolean isOverFlow=false;   // 是否超过9张图片
                //setTittle("正在加载，请稍候",Color.parseColor("#cc0002"),0,false);
                // 获取路径
                ArrayList<String> fileList = new ArrayList<String>();
                fileList = data.getStringArrayListExtra("pathList");
                // 转换成bitmap序列
                for(int i=0;i<fileList.size();i++){
                    //bitmapList.add(BitmapFactory.decodeFile(fileList.get(i),newOpts));
                    if(pathList.size()>=9){
                        isOverFlow=true;
                        break;
                    }
                    pathList.add(fileList.get(i));
                }
                setInputImages();
                setImageClickListener(pathList.size());
                //setTittle("加载完成",Color.parseColor("#5bb531"),2000,false);
                if(isOverFlow)
                    setTittle("加载图片过多，只保留前9张",Color.parseColor("#cc0002"),2000,false);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.write_discovery_menu, menu);
        return true;
        //return super.onCreateOptionsMenu(menu);
    }

    /**
     * 上传新的Discovery信息
     */
    private void commitDiscovery(){
        AVObject avObject = new AVObject("Discovery");
        // 图片
        for(int i=0;i<pathList.size();i++) {
            try {
                AVFile avFile = AVFile.withAbsoluteLocalPath("image" + String.valueOf(i+1), pathList.get(i));
                avObject.put("image" + String.valueOf(i+1),avFile);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        // 内容
        avObject.put("content",content.getText().toString());
        // 用户信息
        // 尝试放置一个用户关联对象
        AVUser avUser = AVUser.getCurrentUser();
        avObject.put("relation_user",avUser);
        //avObject.put("user_name",userObject.getUser_name());
        //avObject.put("user_img_url",userObject.getUri());
        avObject.put("userCode",userObject.getUser_code());
        // 上传
        setTittle("正在上传，请稍候", Color.parseColor("#cc0002"),0,false);
        avObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if(e==null){
                    setTittle("上传成功，正在返回", Color.parseColor("#5bb531"),1000,true);
                }
                else {
                    setTittle("上传失败", Color.parseColor("#cc0002"), 2000, false);
                    isCommitting = false;
                }
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(isCommitting){
            Toast.makeText(getBaseContext(),"正在上传，请等待",Toast.LENGTH_SHORT).show();
            return true;
        }
        int id = item.getItemId();
        if (id == R.id.action_commit) {
            commitDiscovery();
            //Toast.makeText(getBaseContext(),"发布",Toast.LENGTH_SHORT).show();
            return true;
        }
        else if (id == R.id.action_giveup) {
            AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle("确认您的操作")
                    .setMessage("确认放弃发布吗？")
                    .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                        }
                    })
                    .setPositiveButton("继续发布",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            return;
                        }
                    })
                    .show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        if(isCommitting){
            Toast.makeText(getBaseContext(),"正在上传，请等待",Toast.LENGTH_SHORT).show();
            return;
        }
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("确认您的操作")
                .setMessage("确认放弃发布吗？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                })
                .setPositiveButton("继续发布",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        return;
                    }
                })
                .show();
    }

    /**
     * 配置图片按钮
     */
    private void setImageClickListener(int imgNum){
        // 拍照
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 让用户选择拍照还是本地选取图片
                AlertDialog alertDialog = new AlertDialog.Builder(WriteDiscovery.this)
                        .setTitle("选择图片来源")
                        .setNegativeButton("拍照",new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(intent,100);
                            }
                        })
                        .setPositiveButton("图库",new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent();
                                intent.setClass(WriteDiscovery.this,ImgFileListActivity.class);
                                startActivityForResult(intent,101);
                            }
                        })
                        .show();
            }
        };
        // 删除图像
        View.OnClickListener deleteListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteImage(view.getId());
                //Toast.makeText(getBaseContext(),String.valueOf(view.getId()),Toast.LENGTH_SHORT).show();
            }
        };

        image_1.setOnClickListener(deleteListener);
        image_2.setOnClickListener(deleteListener);
        image_3.setOnClickListener(deleteListener);
        image_4.setOnClickListener(deleteListener);
        image_5.setOnClickListener(deleteListener);
        image_6.setOnClickListener(deleteListener);
        image_7.setOnClickListener(deleteListener);
        image_8.setOnClickListener(deleteListener);
        image_9.setOnClickListener(deleteListener);

        switch(imgNum){
            case 0 : image_1.setOnClickListener(listener);break;
            case 1 : image_2.setOnClickListener(listener);break;
            case 2 : image_3.setOnClickListener(listener);break;
            case 3 : image_4.setOnClickListener(listener);break;
            case 4 : image_5.setOnClickListener(listener);break;
            case 5 : image_6.setOnClickListener(listener);break;
            case 6 : image_7.setOnClickListener(listener);break;
            case 7 : image_8.setOnClickListener(listener);break;
            case 8 : image_9.setOnClickListener(listener);break;
            case 9 : break;
            default: break;
        }
    }

    /**
     * 用于删除已经载入的如片
     */
    private void deleteImage(final int id){
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("删除照片")
                .setMessage("确定要删除这张照片吗？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        return;
                    }
                })
                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // 查询点击了那个图片
                        if (image_1.getId() == id) {
                            //bitmapList.remove(0);
                            pathList.remove(0);
                        } else if (image_2.getId() == id) {
                            //bitmapList.remove(1);
                            pathList.remove(1);
                        } else if (image_3.getId() == id) {
                            //bitmapList.remove(2);
                            pathList.remove(2);
                        } else if (image_4.getId() == id) {
                            //bitmapList.remove(3);
                            pathList.remove(3);
                        } else if (image_5.getId() == id) {
                            //bitmapList.remove(4);
                            pathList.remove(4);
                        } else if (image_6.getId() == id) {
                            //bitmapList.remove(5);
                            pathList.remove(5);
                        } else if (image_7.getId() == id) {
                            //bitmapList.remove(6);
                            pathList.remove(6);
                        } else if (image_8.getId() == id) {
                            //bitmapList.remove(7);
                            pathList.remove(7);
                        } else if (image_9.getId() == id) {
                            //bitmapList.remove(8);
                            pathList.remove(8);
                        }
                        setInputImages();
                        setImageClickListener(pathList.size());
                    }
                })
                .show();
    }

    /**
     * 配置图片输入窗口
     */
    private void setInputImages(){
        int imgNum = pathList.size();
        // 首先全部隐藏
        image_1.setVisibility(View.GONE);
        image_2.setVisibility(View.GONE);
        image_3.setVisibility(View.GONE);
        image_4.setVisibility(View.GONE);
        image_5.setVisibility(View.GONE);
        image_6.setVisibility(View.GONE);
        image_7.setVisibility(View.GONE);
        image_8.setVisibility(View.GONE);
        image_9.setVisibility(View.GONE);
        //layout_1.setVisibility(View.GONE);
        layout_2.setVisibility(View.GONE);
        layout_3.setVisibility(View.GONE);
        // 设置显示项
        switch(imgNum){
            case 9 : ;
            case 8 : image_9.setVisibility(View.VISIBLE);
            case 7 : image_8.setVisibility(View.VISIBLE);
            case 6 : image_7.setVisibility(View.VISIBLE);layout_3.setVisibility(View.VISIBLE);
            case 5 : image_6.setVisibility(View.VISIBLE);
            case 4 : image_5.setVisibility(View.VISIBLE);
            case 3 : image_4.setVisibility(View.VISIBLE);layout_2.setVisibility(View.VISIBLE);
            case 2 : image_3.setVisibility(View.VISIBLE);
            case 1 : image_2.setVisibility(View.VISIBLE);
            case 0 : image_1.setVisibility(View.VISIBLE);
            default: break;
        }
        // 根据列表设置图片
        switch (imgNum){
            case 9 : imageLoader.displayImage("file://"+pathList.get(8),image_9,options,null);
            case 8 : imageLoader.displayImage("file://"+pathList.get(7),image_8,options,null);
            case 7 : imageLoader.displayImage("file://"+pathList.get(6),image_7,options,null);
            case 6 : imageLoader.displayImage("file://"+pathList.get(5),image_6,options,null);
            case 5 : imageLoader.displayImage("file://"+pathList.get(4),image_5,options,null);
            case 4 : imageLoader.displayImage("file://"+pathList.get(3),image_4,options,null);
            case 3 : imageLoader.displayImage("file://"+pathList.get(2),image_3,options,null);
            case 2 : imageLoader.displayImage("file://"+pathList.get(1),image_2,options,null);
            case 1 : imageLoader.displayImage("file://"+pathList.get(0),image_1,options,null);
            default: break;
        }
        // 设置最后的加号图片
        switch (imgNum){
            case 0 : image_1.setImageDrawable(getResources().getDrawable(R.drawable.discovery_add_icon));break;
            case 1 : image_2.setImageDrawable(getResources().getDrawable(R.drawable.discovery_add_icon));break;
            case 2 : image_3.setImageDrawable(getResources().getDrawable(R.drawable.discovery_add_icon));break;
            case 3 : image_4.setImageDrawable(getResources().getDrawable(R.drawable.discovery_add_icon));break;
            case 4 : image_5.setImageDrawable(getResources().getDrawable(R.drawable.discovery_add_icon));break;
            case 5 : image_6.setImageDrawable(getResources().getDrawable(R.drawable.discovery_add_icon));break;
            case 6 : image_7.setImageDrawable(getResources().getDrawable(R.drawable.discovery_add_icon));break;
            case 7 : image_8.setImageDrawable(getResources().getDrawable(R.drawable.discovery_add_icon));break;
            case 8 : image_9.setImageDrawable(getResources().getDrawable(R.drawable.discovery_add_icon));break;
            case 9 : break;
            default: break;
        }
    }

    private void imageLoaderInit(){
        File cacheDir = StorageUtils.getOwnCacheDirectory(getBaseContext(), "imageloader/Cache");
        ImageLoaderConfiguration config = new ImageLoaderConfiguration
                .Builder(getBaseContext())
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .discCache(new UnlimitedDiscCache(cacheDir))//自定义缓存路径
                .build();//开始构建
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(config);//全局初始化此配置

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_launcher) //设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.drawable.ic_launcher)//设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.ic_launcher)  //设置图片加载/解码过程中错误时候显示的图片
                //.cacheInMemory(true)						// 设置下载的图片是否缓存在内存中
                //.cacheOnDisk(true)							// 设置下载的图片是否缓存在SD卡中
                //.resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
                //.displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
                .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
                .build();//构建完成
    }

    /**
     * 配置顶部的按钮
     */
    private void setTittle( String text , int color , int time , final boolean isFinish){
        tittle.setText(text);
        tittle.setBackgroundColor(color);
        tittle.setVisibility(View.VISIBLE);

        if(time!=0) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tittle.setVisibility(View.GONE);
                    if(isFinish)
                        finish();
                }
            }, time);
        }
    }
}
